package mongodb

import (
	"context"
	"fmt"
	"log"
	"sync"
	"traning/db_pool_application/pool"
)

var (
	once sync.Once
	instance *Mongodb
)

type Mongodb struct {
}

func GetMongodbInstance() *Mongodb {
	once.Do(func() {
		var mongodbUrl string
		//mongodbUrl = fmt.Sprintf("mongodb://%s:%d/%s", "127.0.0.1", 27017, "aaa")
		mongodbUrl = fmt.Sprintf("mongodb://%s:%s@%s/%s", "aaa", "123456", "127.0.0.1:27017", "test")

		if err := pool.ReisterMgoPool("test", mongodbUrl); err != nil {
			log.Fatal("pool register error, info:", err.Error())
		}
		instance = new(Mongodb)
	})
	return instance
}

func (this *Mongodb) Query(collection string, condition interface{}) ([]map[string]interface{}, error) {
	var docs []map[string]interface{} = make([]map[string]interface{}, 0)
	var ctx = context.Background()
	client, _ := pool.GetMgoClient("test")
	defer pool.PutMgoClient("test", client)
	cur, err := client.Database("test").Collection(collection).Find(ctx, condition)
	if err != nil {
		log.Fatal(err)
		return nil, err
	}
	defer cur.Close(ctx)
	cur.All(ctx, &docs)
	return docs, err
}


